<?php
namespace WebApper\Shortcode;

/*
 * [record_emails id='record_mailBox']
 *
 */
class RecordEmails extends \WebApper\Shortcode {
	
    /**
     * Define shortcode properties
     *
     */
	protected $shortcode = 'record_emails';
	protected $defaults = array(
		'id' => null,		// The unique ID to use for the shortcode. Default: none. Required.
		'tableclasses' => 'table-bordered,table-striped,table-hover,table-condensed',  // Adjusts how the indextable will display. Default: 'table-bordered,table-striped,table-hover,table-condensed'.
	);	

    /**
     * Handles the shortcode
     *
     * @param array $atts
     */
    public function shortcode( $atts ) {

		// Get shortcode attributes
			extract( shortcode_atts( $this->defaults, $atts ) );

		// Check for required shortcode attributes
			$msg = $this->has_req_attrs( $atts );
			if ( $msg !== true )
				return $msg;
			global $wpdb, $webapper;
			$user_ID = get_current_user_id();	
			//=============================== Label Start ============================
					$table = $webapper->tables->email_label;
					$labels = $wpdb->get_results("SELECT * FROM $table  WHERE user_id='$user_ID' ORDER BY created_on DESC");
					$labelList = "";
					$searchLabel =array();						
					foreach ( $labels as $label )
					{
						$labelList .="<li id='lbl_".$label->ID."'><a href='javascript:void(0);' onclick=\'javascript:ChangeLabel(&#39;".$label->label_name."&#39;);\'>".$label->label_name."</a></li>";
						$searchLabel[]= $label->label_name;
					}
			$jsonLabel = json_encode($searchLabel);
			//=============================== Label End =============================
			//======================= START TAG LIST======================
				// Get the fields
			$this->get_fields( $atts );
				// Get the Custom Post Type
			$get_posts_args = array( 'post_type' => 'lead', 'order'=> 'ASC', 'orderby' => 'title', 'posts_per_page' => -1 );  // Set query arguments
			$customPostObjs = get_posts( $get_posts_args );  // Get the posts					
			$customPosts = array();
			$tempFields = array();					
			$taglist = "";
			$searchTag = array();
			foreach($customPostObjs as $post)
			{							
				$taglist.="<li id='tag_".$post->post_title."'><a href='javascript:void(0);' onclick=\'javascript:ChangeTag(&#39;".$post->post_title."&#39;);\'>".$post->post_title."</a></li>";
				$searchTag[] = 	$post->post_title;
			}
			$josnTag = json_encode($searchTag);
			
			//======================= END TAG LIST======================	
			
			//============================= Insert The Compose Email ==========================
				$table = $webapper->tables->emails;
				$tableAttachment = $webapper->tables->email_attachments;
				$tableLabel = $webapper->tables->email_label;
				$filePath = WEB_APPER_DIR_PATH . "email_attachments";
				$submit_status='';
				if(isset($_POST["sendButton"]) || isset($_POST["reply"]))
				{
					$submit_status='Sent';
				}
				else if(isset($_POST["saveButton"]))
				{
					$submit_status='Draft';
				}
				if(isset($_POST['save_lebel']))
				{
					$newLabel=$_POST['newLabel'];
					$sql = $wpdb->prepare( "INSERT INTO {$tableLabel} ( user_id, label_name ) VALUES ( %d, %s)", $user_ID, $newLabel);
					$result = $wpdb->query( $sql );
					
				}
				if(isset($_POST['save_tag']))
				{
					
					$tempIds = rtrim($_POST['recIds'],',');
					$tagName = $_POST['updateTag'];
					$arrayIds = explode(",",$tempIds);
					foreach ($arrayIds as $tempRec)
					{
						//echo ("Hello testing:: ".$tempRec);
						$sql = $wpdb->prepare("update wp_web_apper_emails set tag = %s where user_id = %d and ID = %d",$tagName,$user_ID,$tempRec);
						$result = $wpdb->query( $sql );
					}
					//$newLabel=$_POST['newLabel'];
					//$sql = $wpdb->prepare( "INSERT INTO {$tableLabel} ( user_id, label_name ) VALUES ( %d, %s)", $user_ID, 'Soumen');
				}
				
				else if(isset($_POST["sendButton"]) || isset($_POST['saveButton']) || isset($_POST["reply"]))
				{
					$to = $_POST["recipients_email"];
					$subject = $_POST["subject_email"];
					$message = $_POST['content'];
					$submitTagLabel=$_POST['composeTag'];
					$submitLabel=$_POST['composeLabel']; 
					if($_FILES["filesToUpload"]["tmp_name"][0]!='')
					{
						$isAttachment="Y";
					}
					else
					{
						$isAttachment="N";
					}
					
					$current_date=date("Y-m-d H:i:s");
					$current_time=time();
					$attachments = array();
					$fromEmail = 'jesse@azrto.info';
					$count = 0;
					if($submitLabel !='')
					{
						$finalLabel = $submit_status.','.$submitLabel;
					}
					else
					{
						$finalLabel = $submit_status;
					}
					$sql = $wpdb->prepare( "INSERT INTO {$table} ( user_id, `to`, to_name, `from`, from_name, subject, message_body, attachment_path, tag, label, received_on, date_on ) VALUES ( %d, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %d )", $user_ID, $to, '', $fromEmail, 'Jesse', $subject, htmlspecialchars($message), $isAttachment, $submitTagLabel,$finalLabel, $current_date, $current_time );
										
					$result = $wpdb->query( $sql );
					if ( $result )
					{
						$lastId = $wpdb->insert_id;
						if($isAttachment == 'Y')
						{
							$files = $_FILES["filesToUpload"]["tmp_name"];
							$count=0;
							foreach($_FILES["filesToUpload"]["tmp_name"] as $file_attachment)
							{
								$attachments[$count]["string"] = file_get_contents($file_attachment);
								$attachments[$count]["type"] = $_FILES['filesToUpload']['type'][$count];
								$attachments[$count]["name"] = $_FILES['filesToUpload']['name'][$count];
								if(!is_dir($filePath . "/"))
								{
									mkdir($filePath . "/" , 0777);
									chmod($filePath . "/" , 0777);
								}
								if(!is_dir($filePath . "/" . $lastId))
								{
									mkdir($filePath . "/" . $lastId ."/", 0777);
									chmod($filePath . "/" . $lastId ."/", 0777);
								}
								$maxId = $wpdb->get_results("SELECT ifnull(MAX(ID),0)+1 AS ID FROM $tableAttachment");
								$fileType = wp_check_filetype($_FILES['filesToUpload']['name'][$count]);
								$tempFileName = $maxId[0]->ID.".".$fileType['ext'];
								$sqlAttach = $wpdb->prepare( "INSERT INTO {$tableAttachment} ( emails_id, file_path, file_name ) VALUES ( %d, %s, %s)", $lastId, $tempFileName, $_FILES['filesToUpload']['name'][$count] );
								$resultAttach = $wpdb->query( $sqlAttach );
								$path = $filePath . "/" . $lastId ."/" .$tempFileName;
								move_uploaded_file($file_attachment,$path);
								$count++;	
							}
						}						
					}
										
					if(isset($_POST["sendButton"]) || isset($_POST["reply"]))
					{
						$message = stripslashes("<html><head></head><body>".$message."</body></html>");	
						wp_mail( $to, $subject, $message, array('MIME-Version: 1.0','Content-type: text/html; charset=iso-8859-1'
						,sprintf('From: %s',$fromEmail),sprintf( 'X-Mailer: PHP/%s', phpversion() )), $attachments);
					
					}
				}
			//========================== End Compose Email ====================================
				
			// Build the shortcode output html string
			?>
            <div class="tab-content" id="tags" style="display:none;">
                <div class="tab-pane active fade in" >
                    <table id="tag_list" class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>To</th>
                                <th>From</th> 
                                <th>From Name</th>
                                <th>Subject</th>
                                <th>Message</th> 
                                <th>Tag</th>                   
                                <th>Attachments</th> 
                                <th>Label</th> 
                                <th>Received</th> 
                                <th>Attachment Name</th>
                            </tr>
                    	</thead>
                        <tbody>
                        <?php
                            global $webapper, $wpdb;
							$tagValue = get_post( $_GET['postID'], 'ARRAY_A');							
							$table = $wpdb->prefix . 'web_apper_emails';								
                            $tags = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table} WHERE tag = %s", $tagValue['post_title'] ) );															
                            foreach ( $tags as $tag ) :
                               	echo stripslashes("<tr><td>$tag->ID</td><td>$tag->to</td><td>$tag->from</td><td>$tag->from_name</td><td id='$tag->ID' class='linked-field'>$tag->subject</td><td>"); echo stripslashes(htmlspecialchars_decode($tag->message_body));echo stripslashes("</td><td>$tag->tag</td>");							
								if($tag->attachment_path =='Y'):
									echo stripcslashes('<td style="text-align:center;"><input disabled type="checkbox" name="checkbox_'.$tag->ID.'" id="checkbox_'.$tag->ID.'" checked="checked"  /></td>');
								else: 
									echo "<td>&nbsp;</td>";
								endif;							
								echo stripcslashes("<td>$tag->label</td><td>$tag->received_on</td>");
								if($tag->attachment_path =='Y'):
									$attTable = $webapper->tables->email_attachments;
									$allAtt="";
									$attchs = $wpdb->get_results("select * from $attTable where emails_id=$tag->ID");
									foreach($attchs as $val)
									{
										$allAtt = $allAtt.$val->file_name." | ";
									}
									$allAtt = rtrim($allAtt, "| ");
									echo "<td>".$allAtt."</td>";
								else: 
									echo "<td>&nbsp;</td>";
								endif;
								echo "</tr>";
                            endforeach;
                        ?>
                        </tbody>
                    </table>
	            </div>
            </div>
             <!-- Compose Mail -->
            <form id="composeEmail"  action="" method="POST" enctype="multipart/form-data" onsubmit="return postForm('summernote');">
            <div id="composeModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="infoModalLabel" aria-hidden="true">
                <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                 <h3 id="infoModalLabel">Compose Email</h3>                 
                </div>
                <div class="modal-body">
                    <div class="input-group">
                    <span class="input-group-addon">To:</span>
                    <input type="email" name="recipients_email" class="span5" placeholder="Recipients" required="required">
                    </div>
                    <div class="input-group">
                    <span class="input-group-addon">Subject:</span>
                    <input type="text" name="subject_email" class="span5" placeholder="Subject" required="required">
                    </div>
                    	<div>
                        <textarea class="input-block-level" id="summernote" name="content" rows="18">
                        </textarea>
                        </div>
                    </div>                                       
                <div class="modal-footer">
                     	<div class="span3 btn-group">
                            <input type="submit" id="send_<?php echo $id; ?>_compose" name="sendButton" class="btn  btn-primary" value="Send" />
                            <input type="submit" id="save_<?php echo $id; ?>_compose" name="saveButton" class="btn  btn-primary" value="Save" />  
                            <input name="filesToUpload[]" id="filesToUpload" type="file" multiple="multiple" style="width: 185px" />   
                         </div>
                     	 <div class="span1">
                            	<input class="span1" type="text" data-provide="typeahead" name="composeTag" data-items="4" placeholder="Tag" autocomplete="off"  data-source='<?php echo $josnTag; ?>' />
                        </div>
                         <div class="span1">
                            <input class="span1" type="text" data-provide="typeahead" name="composeLabel" data-items="4" placeholder="Label" autocomplete="off"  data-source='<?php echo $jsonLabel; ?>' />
                        </div>
                        </div>
           	</div>
            </form>
		<!--            End Of Compose Email-->
            
            <!-- Div Modal Popup Start -->
                 <div id="viewModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="infoModalLabel" aria-hidden="true">
                <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                 <h3 id="infoModalLabel">View Email</h3>
                </div>
                <div class="modal-body">
                    <div class="input-group">
                    <span class="input-group-addon">To:</span>
                    <input type="text" name="recipients_email" id="recipients_email" class="span5" placeholder="Recipients" />
                    </div>
                    <div class="input-group">
                    <span class="input-group-addon">Subject:</span>
                    <input type="text" name="subject_email" id="subject_email" class="span5" placeholder="Subject" />
                    </div>
                    	<div>
                        <textarea class="input-block-level" id="edit_summernote" name="content" rows="18">
                        </textarea>
                    	</div>
                    </div>
                 <div class="modal-footer">
                 	<button class="btn btn-primary" data-dismiss="modal" aria-hidden="true">Close</button>
                 </div>   
                 </div>
                  <!-- Div Modal Popup End --> 
            <script type="text/javascript">
				nTable = jQuery('#tag_list');	
				jQuery(document).ready(function($) {
					$('#summernote').summernote({
						  height: 150,   //set editable area's height
						  focus: true    //set focus editable area after Initialize summernote
						});
					$('#edit_summernote').summernote({
						  height: 150,   //set editable area's height
						  focus: true    //set focus editable area after Initialize summernote
						});
					oTable = $(nTable).dataTable({
						<?php
							// Build the sDom parameter for dataTables
							global $template;
							if ( stristr($template, 'fullwidth') ) :
								$spanA = 6; $spanB = 6;
							else :
								$spanA = 4; $spanB = 5;
							endif;
							echo "'sDom': \"<'row' <'toolbar' <'#operationLabel'> <'span2' C><'span".$spanB."'fl>r>>t<'row'<'span".$spanA."'i><'span".$spanB."'p>>\",\n";
						?>
						'sPaginationType': 'bootstrap',
						'aaSorting': [[ 9, 'desc']],
						'oLanguage': {
							'sLengthMenu': 'records per page <select>'+
							'<option value="10">10</option>'+
							'<option value="20">20</option>'+
							'<option value="30">30</option>'+
							'<option value="40">40</option>'+
							'<option value="50">50</option>'+
							'<option value="100">100</option>'+
							'</select>'
						},
						'aoColumnDefs': [ { 'bVisible': false, 'aTargets': [  0, 5, 7, 10 ] } ],
						'oColVis': {
							'buttonText': 'Columns',
							'bRestore': true,
							'sAlign': 'left',
							'sSize': 'css',
							'aiExclude': [ 0, 8, 4 , 10]
						},
					});
					$("#operationLabel").addClass("btn-group span4");
					$("#operationLabel").html("<button id='compose_<?php echo $id; ?>_datatable' class='btn  btn-primary'>Compose</button>");	
						
					$("#tag_list tbody td.linked-field").each( function( e ) {						
							if ( $(this).attr('id') ) {
									var contents = $(this).html();									
							contents = '<a href="javascript:void(0);" id="editMessage_'+$(this).attr('id')+'" class="editMessage_'+$(this).attr('id')+'">' + contents + '</a>';
									$(this).html(contents );
							}					
					});
					$("#tag_list").on('click', "tbody tr td a", function(e) {
						var viewId =($(this).attr('id').split("_")[1]);						
						$.ajax({									
							url: "<?php echo site_url('wp-admin/admin-ajax.php'); ?>",
							type: "post",
							data: {action: 'web_apper<?php echo $this->shortcode; ?>', 'web_apper_nonce':'<?php echo wp_create_nonce( 'WebApperAwesomeness!87' ); ?>', emailId:viewId, status:"LoadEmail"},
							success: function(data) {									
									var finalData = data.split("*!*!*");				
									$("#recipients_email").val(finalData[0]);	
									$("#subject_email").val(finalData[1]);
									$("#edit_summernote").code(finalData[2]);
								},
							error: function (xhr, ajaxOptions, thrownError) {
									alert(xhr.status+': '+thrownError);
								}
							});					
						$("#viewModal").modal();
					});
					$('#viewModal').on('show', function () {
					   $(this).find('.modal-body').css({
							  width:'95%', //probably not needed
							  height:'80%', //probably not needed 
							  'max-height':'100%'
					   });
					});
					$("#compose_<?php echo $id; ?>_datatable").on('click', function(){
						$("#composeModal").modal();						
					});					
				});
				var postForm = function(id) {
						var content = jQuery('textarea[name="content"]').val(jQuery('#'+id+'').code());
					}
			</script>
            <?php
	}

    /**
     * Handles ajax requests
     *
     * @since 1.0
     */
	function sendAjaxResponse() {
		check_ajax_referer( 'WebApperAwesomeness!87', 'web_apper_nonce' );  // Verify the security nonce
		if ( $_POST['status'] == 'LoadEmail' ) :
			global $webapper, $wpdb;                            
			$table = $wpdb->prefix . 'web_apper_emails';
			$query = $wpdb->prepare("SELECT * FROM $table WHERE ID = %d", $_POST['emailId'] );
			$results = $wpdb->get_results( $query, 'ARRAY_A' );
			preg_match_all("/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i",$results[0]['to'], $matchResult);
			$matchResult = array_unique($matchResult[0]);	
			echo $matchResult[0]."*!*!*".$results[0]['subject']."*!*!*".stripcslashes(htmlspecialchars_decode($results[0]['message_body']));
    		exit();
		endif;
		//die();  // Prevents ajax from returning a '0'
	}  

}
$initialize = new RecordEmails(); 

?>